package com.ordobill.webapp.common;

import java.text.*;
import java.util.*;

public class DateUtil {
	public static Calendar getSystemDate() {
		Calendar cal = Calendar.getInstance();
        cal.setTime(new Date(System.currentTimeMillis()));
        
        return cal;
	}
	
	public static String getCurrentDate() {
        return format(getSystemDate(), "yyyy-MM-dd");
    }
	
	public static String getCurrentDate(String format) {
        return format(getSystemDate(), format);
    }
	
	public static Date parse(String date, String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		try {
			return sdf.parse(date);	
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static String format(Calendar cal, String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(cal.getTime());
	}
	
	public static String format(String s, String format) {
		Calendar c = toCalendar(s);
		return format(c, format);
	}
	
	public static Calendar toCalendar(String date) {
		Calendar cal = Calendar.getInstance();
		
		if (date.length() == 8)
			cal.setTime(parse(date, "yyyyMMdd"));
		else if (date.length() == 7)
			cal.setTime(parse(date, "yyyy-MM"));
		else if (date.length() == 10)
			cal.setTime(parse(date, "yyyy-MM-dd"));
		else if (date.length() == 12)
			cal.setTime(parse(date, "yyyyMMddHHmm"));
		else if (date.length() == 14)
			cal.setTime(parse(date, "yyyyMMddHHmmss"));

		return cal;
	}
	
	public static String add(String date, int field, int amount) {
		Calendar cal = toCalendar(date);
		cal.add(field, amount);
		
		if (date.length() == 8)
			return format(cal, "yyyyMMdd");
		if (date.length() == 7)
			return format(cal, "yyyy-MM");
		else 
			return format(cal, "yyyy-MM-dd");
    }
}
